import { Reducer } from "redux";
import { Effect } from "dva";
import { stringify } from "querystring";
import router from "umi/router";

import { fakeAccountLogin, shopuserLogin } from "@/services/login";
import { setAuthority } from "@/utils/authority";
import { getPageQuery } from "@/utils/utils";

export interface StateType {
  status?: "ok" | "error";
  type?: string;
  currentAuthority?: "user" | "guest" | "admin";
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    login_admin: Effect;
    login_sh: Effect;
    login_user: Effect;
    login_query: Effect;
    getCaptcha: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: "login",

  state: {
    status: undefined
  },

  effects: {
    *login({ payload }, { call, put }) {
      console.log(payload);
      fakeAccountLogin(payload)
        .then(response => {
          if (response.code === 0) {
            window.localStorage.setItem(
              "userInfo",
              JSON.stringify(response.data)
            );
            let res = {
              status: "ok",
              type: "account",
              currentAuthority: "user"
            };
            put({
              type: "changeLoginStatus",
              payload: res
            });
            window.location.href = "/#/cjClient/cj";
          }
        })
        .catch(() => {
          let res = {
            status: "ok",
            type: "account",
            currentAuthority: "user"
          };
          put({
            type: "changeLoginStatus",
            payload: res
          });
        });
    },

    *login_admin({ payload }, { call, put }) {
      console.log(payload);
      const response = yield call(fakeAccountLogin, payload);
      // Login successfully
      if (response.code === 0) {
        window.localStorage.setItem("userInfo", JSON.stringify(response.data));
        let res = {
          status: "ok",
          type: "account",
          currentAuthority: "user"
        };
        yield put({
          type: "changeLoginStatus",
          payload: res
        });
        setTimeout(() => {
          window.location.href =
            window.location.href.split("#")[0] + "#/admin/prize/list";
        }, 1000);
      }
    },
    *login_sh({ payload }, { call, put }) {
      const response = yield call(shopuserLogin, payload);
      // Login successfully
      if (response.code === 0) {
        // if(process.env.NODE_ENV=="development"){
        //   document.cookie = 'token='+response.data.Token+';path=/';
        // }

        window.localStorage.setItem("userInfo", JSON.stringify(response.data));
        let res = {
          status: "ok",
          type: "account",
          currentAuthority: "shanghu"
        };
        yield put({
          type: "changeLoginStatus",
          payload: res
        });
        const IsPCBool = IsPC();
        console.log(IsPCBool);
        if (IsPCBool) {
          window.location.href =
            window.location.href.split("#")[0] + "/#/admin/m_shanghu/ll";
        } else {
          window.location.href =
            window.location.href.split("#")[0] + "/#/shanghuclient/dhlb";
        }
      }
      if (payload.mobile == "user") {
        let res = {
          status: "ok",
          type: "account",
          currentAuthority: "user"
        };
        yield put({
          type: "changeLoginStatus",
          payload: res
        });
        window.location.href =
          window.location.href.split("#")[0] + "/#/userClient/jp";
      }
    },
    *login_user({ payload }, { call, put }) {
      console.log(payload);
      fakeAccountLogin(payload)
        .then(response => {
          // Login successfully
          console.log(response);
          if (response.code === 0) {
            if (process.env.NODE_ENV == "development") {
              document.cookie = "token=" + response.data.Token + ";path=/";
            }

            window.localStorage.setItem(
              "userInfo",
              JSON.stringify(response.data)
            );
            let res = {
              status: "ok",
              type: "account",
              currentAuthority: "user"
            };
            put({
              type: "changeLoginStatus",
              payload: res
            });
            window.location.href =
              window.location.href.split("#")[0] + "/#/cjClient/cj";
          } else {
          }
        })
        .catch(() => {
          let res = {
            status: "ok",
            type: "account",
            currentAuthority: "user"
          };
          put({
            type: "changeLoginStatus",
            payload: res
          });
        });
    },
    *login_query({ payload }, { call, put }) {
      console.log(payload);
      fakeAccountLogin(payload)
        .then(response => {
          // Login successfully
          console.log(response);
          if (response.code === 0) {
            if (process.env.NODE_ENV == "development") {
              document.cookie = "token=" + response.data.Token + ";path=/";
            }

            window.localStorage.setItem(
              "userInfo",
              JSON.stringify(response.data)
            );
            let res = {
              status: "ok",
              type: "account",
              currentAuthority: "user"
            };
            put({
              type: "changeLoginStatus",
              payload: res
            });
            window.location.href =
              window.location.href.split("#")[0] + "/#/query";
          } else {
          }
        })
        .catch(error => {
          let res = {
            status: "ok",
            type: "account",
            currentAuthority: "user"
          };
          put({
            type: "changeLoginStatus",
            payload: res
          });
        });
    },
    *getCaptcha({ payload }, { call }) {},

    logout() {
      const { redirect } = getPageQuery();
      // Note: There may be security issues, please note
      window.localStorage.clear();
      if (window.location.pathname !== "/user/login" && !redirect) {
        window.location.href =
          window.location.href.split("#")[0] + "/#/adminlogin";
      }
    }
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type
      };
    }
  }
};

export default Model;

function IsPC() {
  var userAgentInfo = navigator.userAgent;
  var Agents = [
    "Android",
    "iPhone",
    "SymbianOS",
    "Windows Phone",
    "iPad",
    "iPod"
  ];
  var flag = true;
  for (var i = 0; i < Agents.length; i++) {
    if (userAgentInfo.indexOf(Agents[i]) != -1) {
      flag = false;
      break;
    }
  }
  return flag;
}
